package cn.csg.iotplatform.module.system.service.menu;

import cn.csg.iotplatform.framework.common.util.object.BeanUtils;
import cn.csg.iotplatform.module.system.controller.admin.menu.vo.MenuCollectionVO;
import cn.csg.iotplatform.framework.web.core.util.WebFrameworkUtils;
import cn.csg.iotplatform.module.system.controller.admin.menu.vo.SystemMenuReqVO;
import cn.csg.iotplatform.module.system.dal.dataobject.menu.MenuCollectionDO;
import cn.csg.iotplatform.module.system.dal.mysql.menu.MenuCollectionMapper;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Description TODO
 * @Author super huang
 * @Date 2024-05-09 11:16
 */
@Service
@Slf4j
public class SystemMenuServiceImpl implements SystemMenuService {

    @Resource
    private MenuCollectionMapper menuCollectionMapper;

    @Override
    public Object menuCollectionOrNot(SystemMenuReqVO systemMenuReqVO) {
        try {
            if (StringUtils.isEmpty(systemMenuReqVO.getUserId())) return "用户id不能为空";
            if (StringUtils.isEmpty(systemMenuReqVO.getType())) return "收藏类型不能为空";
            if (systemMenuReqVO.getMenuId() == null) return "菜单id不能为空";

            if (StringUtils.equals(systemMenuReqVO.getType(), "1")) {//收藏
                QueryWrapper<MenuCollectionDO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", systemMenuReqVO.getUserId())
                        .eq("type", "1")
                        .eq("menu_id", systemMenuReqVO.getMenuId())
                        .eq("title", systemMenuReqVO.getTitle());
                List<MenuCollectionDO> menuCollectionDOS = menuCollectionMapper.selectList(queryWrapper);
                if (menuCollectionDOS != null && menuCollectionDOS.size() != 0) return "该标题已收藏";
                MenuCollectionDO menuCollectionDO = MenuCollectionDO.builder()
                        .id(UUID.randomUUID().toString())
                        .userId(systemMenuReqVO.getUserId())
                        .type(systemMenuReqVO.getType())
                        .menuId(systemMenuReqVO.getMenuId())
                        .url(systemMenuReqVO.getUrl())
                        .title(systemMenuReqVO.getTitle())
                        .createTime(LocalDateTime.now())
                        .build();

                menuCollectionMapper.insert(menuCollectionDO);

                QueryWrapper<MenuCollectionDO> queryNewWrapper = new QueryWrapper<>();
                queryNewWrapper.eq("user_id", systemMenuReqVO.getUserId())
                        .eq("type", "1");
                menuCollectionDOS = menuCollectionMapper.selectList(queryNewWrapper);
                return getTopParentMenu(menuCollectionDOS);

            } else if (StringUtils.equals(systemMenuReqVO.getType(), "2")) {//取消
                if (StringUtils.isEmpty(systemMenuReqVO.getTitle())) return "取消收藏菜单标题不能为空";
                QueryWrapper<MenuCollectionDO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", systemMenuReqVO.getUserId())
                        .eq("type", "1")
                        .eq("menu_id", systemMenuReqVO.getMenuId())
                        .eq("title", systemMenuReqVO.getTitle());
                menuCollectionMapper.delete(queryWrapper);

                QueryWrapper<MenuCollectionDO> queryNewWrapper = new QueryWrapper<>();
                queryNewWrapper.eq("user_id", systemMenuReqVO.getUserId())
                        .eq("type", "1");
                List<MenuCollectionDO> menuCollectionDOS = menuCollectionMapper.selectList(queryNewWrapper);
                return getTopParentMenu(menuCollectionDOS);
            }
            return "收藏类型非法";
        } catch (Exception e) {
            return e.toString();
        }
    }

    @Override
    public Object selectMenuCollections(String userId) {
        if (StringUtils.isEmpty(userId)) return "用户id不能为空";
        QueryWrapper<MenuCollectionDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("type", "1");
        List<MenuCollectionDO> menuCollectionDOS = menuCollectionMapper.selectList(queryWrapper);
        if (menuCollectionDOS == null && menuCollectionDOS.size() == 0) return "无收藏菜单";
        return getTopParentMenu(menuCollectionDOS);
    }

    private List<MenuCollectionVO> getTopParentMenu(List<MenuCollectionDO> menuCollectionDOS) {
        // 补全最上级父菜单信息
        List<MenuCollectionVO> list = new ArrayList<>();
        for(MenuCollectionDO collectionDO : menuCollectionDOS) {
            MenuCollectionVO menuCollectionVO = BeanUtils.toBean(collectionDO, MenuCollectionVO.class);
            List<MenuCollectionVO> parentDataList = menuCollectionMapper.getMaxparentData(collectionDO.getMenuId());
            if(CollectionUtils.isNotEmpty(parentDataList)) {
                if(parentDataList.size() == 1) {
                    menuCollectionVO.setParentMenuName(parentDataList.get(0).getParentMenuName());
                } else {
                    for(MenuCollectionVO parentData : parentDataList) {
                        if(parentData.getLevel().equals("2")) {
                            menuCollectionVO.setSecondMenuName(parentData.getParentMenuName());
                        } else {
                            menuCollectionVO.setParentMenuName(parentData.getParentMenuName());
                        }
                    }
                }
            }
            list.add(menuCollectionVO);
        }
        return list;
    }

    @Override
    public String menuHistoryCollections(SystemMenuReqVO systemMenuReqVO) {
        try {
            if (StringUtils.isEmpty(systemMenuReqVO.getUserId())) return "用户id不能为空";
            if (StringUtils.isEmpty(systemMenuReqVO.getAccessTime())) return "访问时间不能为空";
            if (systemMenuReqVO.getMenuId() == null) return "菜单id不能为空";
            String dateFormat = "yyyy-MM-dd HH:mm:ss";
            boolean isValidFormat = isValidDateFormat(systemMenuReqVO.getAccessTime(), dateFormat);
            if (!isValidFormat) return "访问时间格式错误，正确格式：yyyy-MM-dd HH:mm:ss";

            QueryWrapper<MenuCollectionDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", systemMenuReqVO.getUserId())
                    .eq("type", "0")
                    .eq("title", systemMenuReqVO.getTitle());
            List<MenuCollectionDO> menuCollectionDOS = menuCollectionMapper.selectList(queryWrapper);
            if (menuCollectionDOS != null && menuCollectionDOS.size() > 0) {
                for (MenuCollectionDO menuCollectionDO : menuCollectionDOS) {
                    menuCollectionMapper.deleteById(menuCollectionDO.getId());
                }
            }

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
            LocalDateTime accessTime = LocalDateTime.parse(systemMenuReqVO.getAccessTime(), formatter);

            MenuCollectionDO menuCollectionDO = MenuCollectionDO.builder()
                    .id(UUID.randomUUID().toString())
                    .userId(systemMenuReqVO.getUserId())
                    .type(systemMenuReqVO.getType())
                    .menuId(systemMenuReqVO.getMenuId())
                    .url(systemMenuReqVO.getUrl())
                    .title(systemMenuReqVO.getTitle())
                    .accessTime(accessTime)
                    .createTime(LocalDateTime.now())
                    .build();

            menuCollectionMapper.insert(menuCollectionDO);
            return "历史记录成功";
        } catch (Exception e) {
            return e.toString();
        }
    }

    @Override
    public Object selectMenuHistory() {
        try {
            String userId = WebFrameworkUtils.getLoginUserId() + "";
            QueryWrapper<MenuCollectionDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .eq("type", "0")
                    .orderByAsc("access_time");
            List<MenuCollectionDO> menuCollectionDOS = menuCollectionMapper.selectList(queryWrapper);
            if (menuCollectionDOS == null || menuCollectionDOS.size() == 0) {
                return "无菜单历史记录";
            }

            // 如果历史记录数量超过15条，删除旧数据，保留最新的15条记录
            if (menuCollectionDOS.size() > 10) {
                int deleteCount = menuCollectionDOS.size() - 10;
                for (int i = 0; i < deleteCount; i++) {
                    MenuCollectionDO toDelete = menuCollectionDOS.get(i);
                    // 删除数据库中对应的记录
                    menuCollectionMapper.deleteById(toDelete.getId());
                }
            }
            // 重新查询最新的10条记录
            QueryWrapper<MenuCollectionDO> queryWrappers = new QueryWrapper<>();
            queryWrappers.eq("user_id", userId)
                    .eq("type", "0")
                    .orderByDesc("access_time");
            menuCollectionDOS = menuCollectionMapper.selectList(queryWrappers);
            return menuCollectionDOS;
        } catch (Exception e) {
            return e.toString();
        }
    }

    public static boolean isValidDateFormat(String value, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setLenient(false); // 设置严格解析

        try {
            // 尝试解析字符串
            sdf.parse(value);
            return true;
        } catch (Exception e) {
            // 解析失败，返回 false
            return false;
        }
    }
}
